import { childrenProps, BasicForm, FormKeys } from '@/components/ProForm/interface/index';
import { ProTableValue } from '@/interface/public';
import { PublicParams } from '@/api/interface/publicParams';
import { RoleInterface } from '@/api/interface/auth/role';

export function useBindingRoleForm(proTableBox: ProTableValue) {
  let bindingRoleForm = reactive<BasicForm<PublicParams.ResBindingId>>({
    form: {
      targetId: null,
      bindingIds: []
    },
    title: '',
    visible: false,
    options: [
      {
        label: '用户id',
        prop: 'targetId',
        hide: true,
        type: 'input',
        defaultValue: ''
      },
      {
        type: 'select',
        label: '角色绑定',
        hide: false,
        prop: 'bindingIds',
        attrs: {
          clearable: true,
          multiple: true
        },
        children: [],
        defaultValue: []
      }
    ]
  });

  /**
   * 获取角色列表
   */
  const setBindingFormChildren = async (params: PublicParams.ReqId) => {
    const res = await promiseAllApi([roleFindList(), roleFindListByUserId(params)]);
    const children: Map<FormKeys<PublicParams.ResBindingId>, childrenProps[]> = new Map();

    children.set('bindingIds', arrTransitionSelectData<RoleInterface.RoleInfo>(res[0], 'name', 'id'));

    bindingRoleForm.form.bindingIds = res[1];
    formSetChildren<PublicParams.ResBindingId>(bindingRoleForm, children);
  };

  const saveAddBindingRoleForm = async (form: PublicParams.ResBindingId) => {
    await roleUserBindingRole(form);
    bindingRoleForm.visible = false;
    elMessage();
    proTableBox.value?.getTableList();
  };

  return { bindingRoleForm, saveAddBindingRoleForm, setBindingFormChildren };
}
